package com.business_clean.ui.activity.depart;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.data.mode.members.MembersDetailEntity;
import com.business_clean.databinding.ActivityQuickDepartBinding;
import com.business_clean.ui.activity.PreviewPhotoActivity;
import com.business_clean.ui.activity.project.AddCompanyProjectActivity;
import com.business_clean.ui.adapter.GridImageAdapter;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import me.hgj.mvvmhelper.base.BaseViewModel;
import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class QuickDepartActivity extends BaseActivity<ProjectMembersViewModel, ActivityQuickDepartBinding> {

    private String[] strings = {"拍照", "相册"};
    private String[] types = {"自愿离职", "处罚离职", "病休离职", "事假离职"};
    private GridImageAdapter mAdapter;

    final int MAX_CHARACTERS = 150; // 最大字符数限制

    private int reason;

    private String uuid = "";

    private LoadingPopupView loadingPopup;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().getExtras() != null) {
            uuid = getIntent().getExtras().getString("uuid");
            String application_no = getIntent().getExtras().getString("application_no");
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("is_work_info", "1");
            if (!TextUtils.isEmpty(uuid)) {
                hashMap.put("uuid", uuid);
                mViewModel.requestStaffDetail(hashMap);
            }
            if (!TextUtils.isEmpty(application_no)) {
                hashMap.put("application_no", application_no);
                mViewModel.requestDepartList(hashMap);
            }
        }
        mAdapter = new GridImageAdapter(this);
        mAdapter.setSelectMax(9);
        mDatabind.pic.recyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mDatabind.pic.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));
        mDatabind.pic.recyclerview.setAdapter(mAdapter);
        mDatabind.bottom.butBase.setText("提交");
    }

    @Override
    public void onBindViewClick() {
        //相册列表
        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
            }

            @Override
            public void openPicture() {
                showBottomSelectedPic();
            }
        });

        //离职类型
        mDatabind.withDepartType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showBottomListWith(QuickDepartActivity.this, 20, "请选择离职类型", types, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        reason = position + 1;
                        mDatabind.withDepartType.setTvRightText(text);
                    }
                });
            }
        });
        //合作结束日期
        mDatabind.withEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showDialogTimePickerView(QuickDepartActivity.this, "用工结束时间", null, 2000, 2099, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        mDatabind.withEndDate.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });
        mDatabind.bottom.butBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("uuid", "" + uuid);
                hashMap.put("work_end_time", "" + mDatabind.withEndDate.getTvRight());
                hashMap.put("reason", "" + reason);
                hashMap.put("remark", "" + mDatabind.remark.editRemark.getText().toString());
                if (mAdapter.getData().size() > 0) {
                    hashMap.put("pic_list", JSON.toJSONString(mAdapter.getData()));
                }
                mViewModel.requestMembersDepart(hashMap);
            }
        });
    }


    @Override
    public void initObserver() {
        mDatabind.remark.editRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int currentCount = s.length();
                if (currentCount > MAX_CHARACTERS) {
                    // 如果超出限制，则阻止用户输入并截断字符串
                    String truncatedText = s.toString().substring(0, MAX_CHARACTERS);
                    mDatabind.remark.editRemark.setText(truncatedText);
                    mDatabind.remark.editRemark.setSelection(MAX_CHARACTERS); // 将光标移动到末尾
                    currentCount = MAX_CHARACTERS;
                }
                mDatabind.remark.tvEditNumber.setText(currentCount + "/" + MAX_CHARACTERS);
            }
        });
    }


    @Override
    public void onRequestSuccess() {
        //快速离职
        mViewModel.getDepart().observe(this, new Observer<Object>() {
            @Override
            public void onChanged(Object o) {
                ToastUtil.show("操作成功");
                AppExtKt.finishActivity(QuickDepartActivity.class);
            }
        });

        mViewModel.getMembersDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                mDatabind.withName.setTvRightText(membersDetailEntity.getUser_name());
                mDatabind.withProject.setTvRightText(membersDetailEntity.getProject_name());
                mDatabind.withJob.setTvRightText(membersDetailEntity.getWork_info().getJob_name());
                mDatabind.withStartWorkDate.setTvRightText(membersDetailEntity.getWork_info().getWork_start_time());
            }
        });
        //获取详情
        mViewModel.getDepartDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                mDatabind.withName.setTvRightText(membersDetailEntity.getUser_name());
                mDatabind.withProject.setTvRightText(membersDetailEntity.getProject_name());
                mDatabind.withJob.setTvRightText(membersDetailEntity.getWork_info().getJob_name());
                mDatabind.withStartWorkDate.setTvRightText(membersDetailEntity.getWork_info().getWork_start_time());
                //离职的信息
                mDatabind.withEndDate.setTvRightText(membersDetailEntity.getLeft_date());
                mDatabind.withDepartType.setTvRightText(membersDetailEntity.getLeft_reason_name());
                mDatabind.remark.editRemark.setText(membersDetailEntity.getLeft_reason_remark());

                for (int i = 0; i < strings.length; i++) {
                    if (strings[i].equals((membersDetailEntity.getLeft_reason_name()))) {
                        reason = (i + 1);
                        break;
                    }
                }

                for (String url : membersDetailEntity.getLeft_pic_list()) {
                    mAdapter.addItemData(url);
                }
            }
        });
    }

    /**
     * 打开相册，让选择
     */
    private void showBottomSelectedPic() {
        CommonUtils.showBottomListWith(this, 20, "", strings, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                switch (position) {
                    case 0:
                        ChoosePicUtil.openCameraTake(QuickDepartActivity.this);
                        break;
                    case 1:
                        ChoosePicUtil.openAlbum(QuickDepartActivity.this, 9 - mAdapter.getData().size());
                        break;
                }
            }
        });
    }

    private void uploadPictures(ArrayList<LocalMedia> result) {

        LoadingDialogExtKt.showLoadingExt(this, "上传中");

        ArrayList<String> strings1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            strings1.add(result.get(i).getCompressPath());
        }

        UploadFileHelper.getInstance().uploadFiles(this, strings1, UploadFileHelper.PATH_HEADER_CUSTOM, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String url) {
                mAdapter.getData().add(url);
                mAdapter.notifyDataSetChanged();
                LoadingDialogExtKt.dismissLoadingExt(QuickDepartActivity.this);
            }

            @Override
            public void onUploadFailed(String errorMessage) {
                LogExtKt.logE("失败  ： " + errorMessage, "七牛云上传");
                ToastUtil.show("上传失败，请重新上传");
                LoadingDialogExtKt.dismissLoadingExt(QuickDepartActivity.this);
            }

            @Override
            public void onUploadProgress(int progress) {

            }

        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == PictureConfig.REQUEST_CAMERA) {//相册
                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                Log.e("", "onActivityResult " + result.get(0).getRealPath());
                uploadPictures(result);
            }
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("", "onActivityResult PictureSelector Cancel");
        }
    }
}